#token 生成
from fastapi import Depends,HTTPException,status
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from jose import  jwt,JWTError
from datetime import datetime,timedelta

pwd_context = CryptContext(schemes=["bcrypt"],deprecated="auto")   #加密方式

# 随机密钥
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
# 加密算法
ALGORITHM = "HS256"
# 过期时间





#密码加密方法
def get_hash_pwd(pwd:str):
    return pwd_context.hash(pwd) #把传递过来的密码加密返回


#token生成 token:用户数据，过期时间
def create_token(userinfo,expire_time): #把用户信息 和 当前时间传递进来

      if expire_time:
          expire = datetime.utcnow() + expire_time
      else:
          expire = datetime.utcnow() + timedelta(minutes=30)

      userinfo.update({'exp':expire})
      token = jwt.encode(userinfo,SECRET_KEY,ALGORITHM)   #生成toen
      return token


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
#校验token
def pass_token(token:str=Depends(oauth2_scheme)):
    # print(token)
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="token不正确或者已经过期",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
       jwt_data = jwt.decode(token,SECRET_KEY,algorithms=[ALGORITHM])
       id = jwt_data.get('sub')   #获取key
       if id is None or id == "":
           raise credentials_exception

    except JWTError:
           raise credentials_exception

    return id